package com.example.jcservice.service;

import com.dtflys.forest.http.ForestCookie;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.springboot.annotation.ForestScan;
import com.example.jcservice.client.JcLibrary;
import com.example.jcservice.stType.Resive.Library.LibraryUserInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference;

@Service
@ForestScan(basePackages = "com/example/jcservice/client")
public class LibraryService {
        public String LoginStatus = null;
        private ForestCookie cookie;
        ArrayList booksList = new ArrayList();//用于存放已借书籍书名
        ArrayList<String> userInfo_text = new ArrayList();//用于存放第一步网页爬取的 String数据
        ArrayList<String> userInfo_string = new ArrayList<>();//用于存放 正则表达后的数据

    @Resource
    private JcLibrary lib;

    /**
     * 图书馆登录方法
     * */
    public LibraryUserInfo login(String name, String passBase64) {
        //清空用户详情集合
        userInfo_text.clear();
        userInfo_string.clear();

//        ForestConfiguration configuration = ForestConfiguration.configuration();
//        //configuration.setLogResponseContent(true);//开启打印日志
//        // 通过Forest配置对象实例化Forest请求接口
//        JcLibrary lib = configuration.createInstance(JcLibrary.class);

        //带参访问图书馆登录页，保存cookie
        AtomicReference<ForestCookie> cookieAtomic = new AtomicReference<>(null);
        ForestResponse res = lib.login(name, passBase64, (request, cookies) -> {
            cookieAtomic.set(cookies.allCookies().get(0));
            //将登录获取到到cookie赋值给forest cookie全局变量
            cookie = cookieAtomic.get();
        });

        /**
         * 判断登录是否成功
         * */
        //打印登录请求响应内容，登录成功 返回 OK
        String a = res.getContent();
        LibraryUserInfo UserInfo = new LibraryUserInfo();
        if (a.equals("ok")) {
            LoginStatus = "登录正常";
            System.out.println("登录成功>>>已保存cookie");

            UserInfo = LibraryLogin();

        } else if (a.equals("密码或账号错误")) {
            LoginStatus = "密码或账号错误";
            System.out.println("登录失败>>>" + a);

            UserInfo.setLoginStatus(LoginStatus);
        }

        return UserInfo;
    }

    /**
     * 获取借阅图书方法
     * */
    public void BooksInfo(){
        //在往集合存书时，先清空用于存放书名的集合
        booksList.clear();
        //清空书名
        LibraryUserInfo.booksData.clear();

        //携带cookie访问借阅详情页面
        ForestCookie cookie_index = cookie;
        ForestResponse res_book = lib.bookAfterLogin((request, cookies) -> {
            // 将之前调用登入接口获得的Cookie传入请求发送到服务端
            cookies.addCookie(cookie_index);
        });

        String c = res_book.getContent();
        //把借书详情详情页H5源码c，传给jsoup解析
        Document book_document = Jsoup.parse(c);
        Elements books = book_document.select(".jp-booksList tr td a");


        Elements books1 = book_document.select(".jp-booksList tr td.red");
        System.out.println(books1);

        if (books.size() == 0){
            String out = "没有借书";
            System.out.println(out);
        }else{
            int x = books.size()/2;
            System.out.println("你借了："+x+"本书");
            for(int i=0;i<books.size()/2;i++){
                int t=i*2;
                Element u=books.get(t);
                String p=u.text();
                booksList.add(p);
                LibraryUserInfo.BooksInfo booksInfo = new LibraryUserInfo.BooksInfo();
                booksInfo.setName(p);
                LibraryUserInfo.booksData.add(booksInfo);
                System.out.println(booksList.get(i));
            }
        }
    }

    /**
     * 登录图书馆
     *
     * @return*/
    public LibraryUserInfo LibraryLogin(){
        //携带cookie访问个人详情页面
        ForestResponse userIndex = lib.userIndex((request, cookies) -> {
            // 将之前调用登入接口获得的Cookie传入请求发送到服务端
            cookies.addCookie(cookie);
        });

        String userIndexH5 = userIndex.getContent();
        //获得个人详情资料
        Document document = Jsoup.parse(userIndexH5);
        Elements xm = document.select(".user-dashboard .ud-userInfo .ud-userItem dd");

        //        Element getxm = xm.get(0);
        //        String the_xm = getxm.text();

        for (int n=0;n<xm.size();n++){
            Element textContent = xm.get(n);
            String Content = textContent.text();
            userInfo_text.add(Content);
        }
        //网页元素文本显示例：  姓名：xxx 学号：123456  用正则表达？这里用的时Java字符串截取  截取：之后字符串
        //Java截取某个 字符串后面的 内容写法
        //姓名
        //String str=the_xm.substring(0, the_xm.indexOf("："));
        //String userName=the_xm.substring(str.length()+1, the_xm.length());
        //可借
        //String userAvailable=the_kj.substring(the_kj.indexOf("：")+1, the_kj.indexOf("本"));

        //这两个for语句代替上面写法
        for (int m = 0; m < 5; m++) {
            String lastInfo = userInfo_text.get(m).substring(0, userInfo_text.get(m).indexOf("："));
            String user=userInfo_text.get(m).substring(lastInfo.length()+1);
            userInfo_string.add(user);
            //userInfo_string[5] = [姓名，学号，学院，xx，手机]
        }
        for (int l=0; l<3;l++){
            String book=userInfo_text.get(l+6).substring(userInfo_text.get(l+6).indexOf("：")+1, userInfo_text.get(l+6).indexOf("本"));
            userInfo_string.add(book);
            //userInfo_string[3] = [可借，已借，超期]
        }

        //实例化对象
        LibraryUserInfo UserInfo = new LibraryUserInfo();
        UserInfo.setLoginStatus(LoginStatus);
        UserInfo.setStudentName(userInfo_string.get(0));
        UserInfo.setStudentId(userInfo_string.get(1));
        UserInfo.setFaculty(userInfo_string.get(2));
        UserInfo.setPhoneNumber(userInfo_string.get(4));
        UserInfo.setAvailable(userInfo_string.get(5));
        UserInfo.setBorrowed(userInfo_string.get(6));
        UserInfo.setOvertime(userInfo_string.get(7));
        BooksInfo();//这个方法已经将书的信息set进了UserInfo.setData

        return UserInfo;
    }

}
